package com.example.chatapp11

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class MessageAdapter(private val messages: ArrayList<Message>) : RecyclerView.Adapter<MessageAdapter.MessageViewHolder>() {

    class MessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val userMessageContainer: LinearLayout = itemView.findViewById(R.id.ll_user_message)
        val otherMessageContainer: LinearLayout = itemView.findViewById(R.id.ll_other_message)
        val userMessageText: TextView = itemView.findViewById(R.id.tv_user_message)
        val otherMessageText: TextView = itemView.findViewById(R.id.tv_other_message)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.message_item, parent, false)
        return MessageViewHolder(view)
    }

    override fun onBindViewHolder(holder: MessageViewHolder, position: Int) {
        val message = messages[position]

        if (message.isUserMessage) {
            // Show user message style
            holder.userMessageContainer.visibility = View.VISIBLE
            holder.otherMessageContainer.visibility = View.GONE
            holder.userMessageText.text = message.content
        } else {
            // Show other message style
            holder.userMessageContainer.visibility = View.GONE
            holder.otherMessageContainer.visibility = View.VISIBLE
            holder.otherMessageText.text = message.content
        }
    }

    override fun getItemCount(): Int {
        return messages.size
    }

    fun addMessage(message: Message) {
        messages.add(message)
        notifyItemInserted(messages.size - 1)
    }
}